<template>
   <div class="common-layout">
    <el-container>
      <el-header>
        <h2>欢迎您！{{ store.state.user.userInfo.username }} </h2>
      </el-header>
      <el-container>

        <el-aside width="200px">
          <el-menu
            active-text-color="#ffd04b"
            background-color="#545c64"
            class="el-menu-vertical-demo"
            default-active="1"
            text-color="#fff"
          >
            <el-menu-item index="1">
              <el-icon><icon-menu /></el-icon>
              <span>表格操作</span>
            </el-menu-item>

            <el-menu-item index="2">
              <el-icon><Setting /></el-icon>
              <span>xx操作</span>
            </el-menu-item>
          </el-menu>
        </el-aside>

        <el-main>
          <!-- 面包导航 -->
          <div class="board-nav">

            <el-breadcrumb :separator-icon="ArrowRight">
              <el-breadcrumb-item>首页</el-breadcrumb-item>
              <el-breadcrumb-item>管理</el-breadcrumb-item>
              <el-breadcrumb-item>操作图书数据</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="right">
              <div class="right-l">
                <el-input 
                  v-model="searchKey" 
                  placeholder="请输入查询图书名称的关键字"
                  clearable
                 />
                <el-button type="primary" @click="searchBookFn">
                  <Search style="width: 1em; height: 1em; margin-right: 8px" />
                  查询
                </el-button>
              </div>
              <el-button type="success" @click="handlerClick('add', row)">
                <el-icon><CirclePlus /></el-icon>
                <span>新增</span>
              </el-button>
            </div>

          </div>
          <!-- 表格数据 -->
          <el-table 
            :data="tableData" 
            style="width: 100%; margin-top: 10px;"
            height="500"
          >
            <el-table-column
              v-for="(item,index) in tableHeadTitle"
              :key="index"
              :fixed="index === 0"
              :prop="item.value"
              :label="item.text" 
              :width="item.width"
            />
            <el-table-column fixed="right" label="操作" width="230">
              <template #default="{row}">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handlerClick('details', row)"
                ><el-icon><Promotion /></el-icon>详情</el-button>
                <el-button 
                  type="success" 
                  size="small"
                  @click="handlerClick('update', row)"
                ><el-icon><Tools /></el-icon>编辑</el-button>
                <el-button 
                  type="danger" 
                  size="small"
                  @click="handlerClick('delete', row)"
                ><el-icon><DeleteFilled /></el-icon>删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页操作 -->
          <div class="page-nation">
            <el-pagination 
              background 
              layout="prev, pager, next" 
              :total="initData.length" 
              :page-size="pageSize"
              @current-change="currentChange"
            />
          </div>
        </el-main>
        
      </el-container>
    </el-container>

    <Update
      :params="paramsUpdate"
      :visibleUpdate="visibleUpdate"
      @confirm="confirm"
    />

  </div>
  
  

</template>

<script setup>
// store
import { useStore } from 'vuex';
// element plus
import {
  Menu as IconMenu,
  Setting,
  ArrowRight,
  CirclePlus,
  DeleteFilled,
  Promotion,
  Tools,
  Search
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import tableHeadTitle from './tableTitle'
import { watchEffect, toRefs, nextTick, onBeforeMount } from 'vue';
// utils
import { truncateString } from '@/utils/strUtils.js'
// api
import bookModelApi from '@/request/api/book.js';
// components
import Update from '@/components/manage/Update.vue'

const store = useStore();

// 初始化数据
const initData = ref([]);
// 重构后的数据
let remadeData = ref([]);

// 生命周期
onBeforeMount(() => {
  onUpdateInitPage();
})

// 进入页面调用
function onUpdateInitPage(){
  getNewAllBookList();
  // initData.value = store.state.book.bookList
  setTimeout(() => {
    // getNewAllBookList();
    initData.value = store.state.book.bookList;
    // 重构数据
    remadeData.value = initData.value.map(item => {
      return {
        ...item,
        briefIntro_brief: truncateString(item.briefIntro, 40),
        category_name: store.state.book.cateGoryList.filter(v => {
          return v['category_id'] == item.category_id;
        })[0].category_name,
        status_name: +item.statuss == 1 ? '已上架' : '未上架'
      }
    })
  },500)
}

// 获取/更新所有书籍列表
async function getNewAllBookList(){
  const res = await bookModelApi.getAllBookApi();
  // 更新所有书籍存入vuex中
  // store.commit("setAllBookList", res.data);
  store.dispatch('setNewBookList', res.data);
}


// 当前页码
let newCurrentPage = ref(1);
// 每页条数
const pageSize = 5;

// 表格数据 ==> 分页5条数据
const tableData = computed(() => {
  return remadeData.value.slice((newCurrentPage.value - 1) * pageSize, newCurrentPage.value * pageSize);
})

// 新上好书页码改变
const currentChange = ( page ) => {
  newCurrentPage.value = page;
}

// 传递到update页面的参数
const paramsUpdate = ref({
  type: "add",
  title: "新增",
  data: null,
})

// 显示隐藏update.vue页面
let visibleUpdate = ref(false)

// 表格操作
const handlerClick = (type, row) => {
  // 先把旧对象清空，然后再设置新对象
  paramsUpdate.value = {}
  paramsUpdate.value.type = type;
  if(type === 'add'){
    paramsUpdate.value.title = "新增图书数据";
    paramsUpdate.value.data = null;
    visibleUpdate.value = true;
  }else if (type === "details") {
    paramsUpdate.value.title = "图书详情";
    visibleUpdate.value = true;
    paramsUpdate.value.data = row;
  } else if (type === "delete") {
    clickDelete(row);
  } else if (type === "update") {
    paramsUpdate.value.title = "编辑图书";
    paramsUpdate.value.data = row;
    visibleUpdate.value = true;
  }
}

// 删除操作
const clickDelete = ( model ) => {
  ElMessageBox.confirm(
    '此操作不可逆, 确定执行删除操作吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // 调用删除接口
      const res = await bookModelApi.deleteBookByIdApi({
        book_id: model.book_id
      });
      ElMessage({
        showClose: true,
        type: 'success',
        message: res.msg,
      })
      onUpdateInitPage();
      // location.reload()
    })
    .catch(() => {
      ElMessage({
        showClose: true,
        type: 'info',
        message: '取消操作',
      })
    })
}

// 子传父亲
const confirm = ( model ) => {
  // 关闭弹窗
  visibleUpdate.value = false;
  if( model.type == 'confirm' ){
    // 重新调用请求列表
    onUpdateInitPage();
  }
}

// 查询关键字
const searchKey = ref('');
// 查询
const searchBookFn = () => {
  // console.log('tableData.value', tableData.value)
  remadeData.value = remadeData.value.filter(item => item['book_name'].includes(searchKey.value))
}

watch(searchKey, () => {
  if(searchKey.value.trim() == ''){
    onUpdateInitPage();
  }
})
</script>

<style scoped lang="less">
.common-layout{
  background: rgb(196, 194, 194);
  position: relative;
  .el-header{
    text-align: center;
    line-height: 50px;
  }

  .el-aside{
    height: calc(100vh - 327px);
    .el-menu{
      height: 100%;
    }
  }
  .el-main{
    height: calc(100vh - 327px);
    background: #fff;
    .board-nav{
      display: flex;
      align-items: center;
      justify-content: space-between;
      .right{
        width: 420px;
        display: flex;
        justify-content: space-between;
        .right-l{
          display: flex;
        }
      }
      .el-input{
        width: 250px;
        margin-right: 5px;
      }
    }
    .page-nation {
      padding-top: 10px;
      display: flex;
      justify-content: end;
    }
  }
} 


</style>